package com.ihd.ihardware.view.enter.view;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ihd.ihardware.R;
import com.ihd.ihardware.app.MyApplication;
import com.ihd.ihardware.common.AppConstans;
import com.ihd.ihardware.databinding.ActivityRegistBinding;
import com.ihd.ihardware.pojo.EmptyRes;
import com.ihd.ihardware.pojo.LoginRes;
import com.ihd.ihardware.pojo.UserInfoRes;
import com.ihd.ihardware.view.enter.viewModel.RegistViewModel;
import com.ihd.ihardware.view.tzc.discovery.view.BaseWebActivity;
import com.ihd.ihardware.view.tzc.main.view.BalanceActivity;
import com.ihd.ihardware.view.tzc.me.view.PerInfoActivity;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import cn.jpush.android.api.JPushInterface;
import cn.wowjoy.commonlibrary.app.Constans;
import cn.wowjoy.commonlibrary.base.BaseActivity;
import cn.wowjoy.commonlibrary.base.BaseConsumer;
import cn.wowjoy.commonlibrary.rxbus.RxBus;
import cn.wowjoy.commonlibrary.utils.AppActivityManager;
import cn.wowjoy.commonlibrary.utils.DialogUtils;
import cn.wowjoy.commonlibrary.utils.SPUtils;
import cn.wowjoy.commonlibrary.utils.ToastUtils;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class RegistActivity extends BaseActivity<ActivityRegistBinding, RegistViewModel> {
    private Disposable wxLogin;
    private CountDownTimer timer;

    @Override
    protected void init(Bundle savedInstanceState) {
        mImmersionBar.statusBarDarkFont(true).init();
        binding.mtitlebar.setTitle("注册");
        binding.mtitlebar.setLeftBack(this);

        binding.phoneET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 && binding.codeET.getText().length() > 0 && binding.passwordET.getText().length() > 0)
                    binding.registTV.setEnabled(true);
                else
                    binding.registTV.setEnabled(false);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        binding.codeET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 && binding.phoneET.getText().length() > 0 && binding.passwordET.getText().length() > 0)
                    binding.registTV.setEnabled(true);
                else
                    binding.registTV.setEnabled(false);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        binding.passwordET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0 && binding.phoneET.getText().length() > 0 && binding.codeET.getText().length() > 0)
                    binding.registTV.setEnabled(true);
                else
                    binding.registTV.setEnabled(false);
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        setRx(Constans.CODES, new BaseConsumer<EmptyRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(RegistActivity.this);
            }

            @Override
            protected void onSuccess(EmptyRes mLiveData) {
                DialogUtils.dismiss(RegistActivity.this);
                timer = new CountDownTimer(60 * 1000, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        binding.getCode.setEnabled(false);
                        binding.getCode.setText(millisUntilFinished / 1000 + "s");
                    }

                    @Override
                    public void onFinish() {
                        binding.getCode.setEnabled(true);
                        binding.getCode.setText("重新获取");
                    }
                }.start();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(RegistActivity.this, error.getMessage());
                DialogUtils.dismiss(RegistActivity.this);
            }
        });

        setRx(Constans.REGIST, new BaseConsumer<LoginRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(RegistActivity.this);
            }

            @Override
            protected void onSuccess(LoginRes mLiveData) {
                DialogUtils.dismiss(RegistActivity.this);
                JsonObject mParam = new JsonObject();
                mParam.addProperty("userId", mLiveData.getData().getUserId());
                mParam.addProperty("userToken", mLiveData.getData().getUserToken());
                SPUtils.putString(Constans.GATEWAY_TOKEN, mParam.toString());
                JPushInterface.setAlias(RegistActivity.this, 0, mLiveData.getData().getUserId());
                Intent mIntent = new Intent(RegistActivity.this, PerInfoActivity.class);
                startActivity(mIntent);
                AppActivityManager.getInstance().killActivity(PerActivity.class);
                finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(RegistActivity.this, error.getMessage());
                DialogUtils.dismiss(RegistActivity.this);
            }
        });

        binding.getCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.phoneET.getText().length() == 0)
                    ToastUtils.showShort(RegistActivity.this, "请输入手机号");
                else
                    viewModel.sendVerifySms(binding.phoneET.getText().toString(), "1");
            }
        });

        binding.registTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewModel.regist(binding.phoneET.getText().toString(), binding.passwordET.getText().toString(), binding.codeET.getText().toString());
            }
        });

        binding.wxLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = getPackageName();
                if (!MyApplication.api.isWXAppInstalled()) {
                    ToastUtils.showLong(RegistActivity.this, "请先安装微信客户端");
                    return;
                }
                MyApplication.api.sendReq(req);
            }
        });
        binding.xy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(RegistActivity.this, BaseWebActivity.class);
                i.putExtra("url", "http://html5.zhouchangshu.com/conceal/agreements.html");
                startActivity(i);
            }
        });

        wxLogin = RxBus.getInstance().tObservable(AppConstans.WXLOGIN, String.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String code) throws Exception {
                        viewModel.wxLogin(code);
                    }
                });
        setRx(Constans.LOGIN, new BaseConsumer<LoginRes>() {
            @Override
            protected void onStart() {
                DialogUtils.waitingDialog(RegistActivity.this);
            }

            @Override
            protected void onSuccess(LoginRes mLiveData) {
                JsonObject mParam = new JsonObject();
                mParam.addProperty("userId", mLiveData.getData().getUserId());
                mParam.addProperty("userToken", mLiveData.getData().getUserToken());
                SPUtils.putString(Constans.GATEWAY_TOKEN, mParam.toString());
                JPushInterface.setAlias(RegistActivity.this, 0, mLiveData.getData().getUserId());
                viewModel.getUserInfo();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(RegistActivity.this, error.getMessage());
                DialogUtils.dismiss(RegistActivity.this);
            }
        });

        setRx(AppConstans.INFO, new BaseConsumer<UserInfoRes>() {
            @Override
            protected void onStart() {
            }

            @Override
            protected void onSuccess(UserInfoRes mLiveData) {
                DialogUtils.dismiss(RegistActivity.this);
                if (TextUtils.isEmpty(mLiveData.getData().getWeight())) {
                    Intent mIntent = new Intent(RegistActivity.this, PerInfoActivity.class);
                    mIntent.putExtra("userinfo", mLiveData.getData());
                    startActivity(mIntent);
                } else {
                    SPUtils.putString(AppConstans.USER_INFO, new Gson().toJson(mLiveData.getData(), UserInfoRes.DataBean.class));
                    Intent mIntent = new Intent(RegistActivity.this, BalanceActivity.class);
                    startActivity(mIntent);
                }

                AppActivityManager.getInstance().killActivity(PerActivity.class);
                finish();
            }

            @Override
            protected void onError(Throwable error) {
                ToastUtils.showShort(RegistActivity.this, error.getMessage());
                DialogUtils.dismiss(RegistActivity.this);
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_regist;
    }

    @Override
    protected Class getViewModelClass() {
        return RegistViewModel.class;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null)
            timer.cancel();
    }
}